package com.billionsfinance.hessian.core;

import com.caucho.hessian.client.HessianProxyFactory;

import java.net.MalformedURLException;

/**
 * @author HuGuobo
 * @version V1.0
 * @Title: RemoteCall.java
 * @Package com.billionsfinance.common.framework
 * @Description: 获取远程Hessian对象
 * @date 2015年10月8日 下午5:42:14
 */
public class RemoteCall {

	/**
	 * 获取远程Hessian对象
	 *
	 * @param classType
	 * @param connTimeout
	 * @param readTimeout
	 * @return
	 * @throws Exception
	 * @Name: getRemoteObject
	 * @author: WeiHui.Zhang
	 * @Version: V1.00
	 * @Date: 2016年8月4日上午10:55:30
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getRemoteObject(Class<T> classType, int connTimeout, int readTimeout) {
		ClientInfo clientInfo = HessianCacheManager.getClientInfo(classType.getName());
		if (clientInfo == null) {
			throw new RuntimeException(
					"Interface [" + classType.getName() + "] is not registered in the client table!");
		}
		String url = clientInfo.getAccessUrl();
		HessianProxyFactory factory = new HessianProxyFactory();
		if (readTimeout > 0) {
			factory.setReadTimeout(readTimeout * 1000);
		} else {
			factory.setReadTimeout(clientInfo.getReadTimeout() * 1000);
		}
		T object = null;
		Class<?> interfaceClass = HessianCacheManager.getHessianClientInterfaceClass(clientInfo.getInterfaceName());
		try {
			object = (T) factory.create(interfaceClass, url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return object;
	}

	/**
	 * 获取远程Hessian对象
	 *
	 * @param classType
	 * @return
	 */
	public static <T> T getRemoteObject(Class<T> classType) {
		// 服务组号默认为项目代码
		// String groupNo = GlobalParam.getParam("app_code");
		return getRemoteObject(classType, 0, 0);
	}

	/**
	 * 获取远程Hessian对象
	 *
	 * @param classType
	 * @param groupNo
	 * @return
	 */
	// public static <T> T getRemoteObject(Class<T> classType, String groupNo) {
	// return getRemoteObject(classType, groupNo, 0, 0);
	// }
}
